package com.example.forum_system.service.impl;

import com.example.forum_system.dao.MessageMapper;
import com.example.forum_system.dao.UserMapper;
import com.example.forum_system.model.Message;
import com.example.forum_system.model.VO.MessageVO;
import com.example.forum_system.service.IMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: 0.forum_system
 * @BelongsPackage: com.example.forum_system.service.impl
 * @Author : 游在海里的鱼
 * @CreateTime : 2023-11-13  17:13
 * @Version : 1.0
 * @Description : TODO
 */
@Service
@Slf4j
public class MessageService implements IMessageService {

    @Autowired
    MessageMapper messageMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public int insertMessage(Message message) {
        initialize(message);
        return messageMapper.insertMessage(message);
    }

    @Override
    public List<MessageVO> selectAllMessage(long receiveUserId) {
        List<MessageVO> messageVOList = messageMapper.selectAllMessage(receiveUserId);
        messageMapper.updateStateToRead(receiveUserId);
        addUser(messageVOList);
        return messageVOList;
    }

    @Override
    public int selectUnreadCount(long receiveUserId) {
        return messageMapper.selectUnreadCount(receiveUserId);
    }

    @Override
    public int updateStateToReplied(long id) {
        return messageMapper.updateStateToReplied(id);
    }

    private void addUser(List<MessageVO> messageVOList){
        for(MessageVO message:messageVOList){
            message.setPostUser(userMapper.selectOneById(message.getPostUserId()));
        }
    }
    private void initialize(Message message){

        if(message.getState() == null){
            message.setState(Byte.valueOf("0"));
        }
        if(message.getDeleteState() == null){
            message.setDeleteState(Byte.valueOf("0"));
        }
        if(message.getCreateTime() == null){
            message.setCreateTime(new Date());
        }
        if(message.getUpdateTime() == null){
            message.setUpdateTime(new Date());
        }
    }
}
